package crmdna.payment;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.*;

import paypalnvp.core.PayPal.Environment;
import paypalnvp.fields.*;
import paypalnvp.request.*;

@SuppressWarnings("serial")
public class DoExpressCheckoutServlet extends HttpServlet {

	public void doOptions(HttpServletRequest req, HttpServletResponse resp)
	        throws IOException {
	    resp.setHeader("Access-Control-Allow-Origin", "*");
	    resp.setHeader("Access-Control-Allow-Methods", "POST");
	    resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
	    resp.setHeader("Access-Control-Max-Age", "86400");
	    resp.setHeader("Allow", "POST, OPTIONS");
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setHeader("Access-Control-Allow-Origin", "*");
		
		String token = req.getParameter("token");
		String payerId = req.getParameter("PayerID");
		Response crsp = new Response("Failure");
		PrintWriter pw = resp.getWriter();
		
		if((token != null) && (payerId != null)) {
		
			Map<String, String> response;
			
			VendorPayment vp = new VendorPayment(req.getParameter("vendor"));
			GetExpressCheckoutDetails getEC = new GetExpressCheckoutDetails(token);			
			vp.paypal.setResponse(getEC);
			response = getEC.getNVPResponse();
			System.out.println("GEC: " + response.toString());
			
			if("Success".equals(response.get("ACK"))) {
				PaymentItem item = new PaymentItem();
		        item.setAmount(response.get("AMT").toString());
		        
		        PaymentItem[] items = { item };
				Payment payment = new Payment(items);
				payment.setCurrency(Currency.SGD); // FIXME: Should not hardcode currency
				payment.setNotifyUrl("http://crmdna-payment.appspot.com/ipn" + ((vp.env == Environment.SANDBOX) ? "sandbox" : ""));
				
				String itemName = response.get("L_NAME0");
				String invoiceNumber = response.get("INVNUM");
				
				DoExpressCheckoutPayment doEC = new DoExpressCheckoutPayment(payment, token, PaymentAction.SALE, payerId);
				vp.paypal.setResponse(doEC);
				response = doEC.getNVPResponse();			    
			    System.out.println("DEC: " + response.toString());
			    
			    if("Success".equals(response.get("ACK"))) {
			    	crsp.ack = "Success";
					pw.print(crsp.get(itemName, invoiceNumber, response.get("TRANSACTIONID"), 
							response.get("CURRENCYCODE") + " " + response.get("AMT"), 
							response.get("PAYMENTSTATUS"), response.get("PENDINGREASON")));
			    }
			    else {
					pw.print(crsp.get(response.get("L_SEVERITYCODE0"), response.get("L_ERRORCODE0"), 
					 		 		  response.get("L_SHORTMESSAGE0"), response.get("L_LONGMESSAGE0")));
			    }			    	
			} 
			else {
				pw.print(crsp.get(response.get("L_SEVERITYCODE0"), response.get("L_ERRORCODE0"), 
				 		 		  response.get("L_SHORTMESSAGE0"), response.get("L_LONGMESSAGE0")));
			}
		}
		else {
			pw.print(crsp.get("Error", "12345", "Error processing " + token + "/" + payerId, ""));			
		}
		
		pw.close();
	}
}
